package com.store.app.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.GuideShoppingAgreeAdapter;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.GuideShoppingAgreeBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.widget.AutoListView;
import com.store.app.widget.AutoListView.OnLoadListener;
import com.store.app.widget.AutoListView.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 已批准
 */
public class TheGuideAgreeFragment extends Fragment implements IOnHttpListener {
    private View v;
    private AutoListView lv;
    private List<GuideShoppingAgreeBean> list;
    private GuideShoppingAgreeAdapter mAdapter;
    //无网络页面
    private LinearLayout lin_loadfail;
    private ImageView img_fail_nonet;
    private ImageView img_fail_notext;
    private TextView tv_fail;
    private static final int MSG_LOAD_SUCCESS = 0;
    private static final int MSG_LOAD_FAILED = 1;
    private static final int MSG_REFRESH_SUCCESS = 2;
    private static final int MSG_REFRESH_FAILED = 3;


    private static final int MSG_DELETE_SUCCESS = 6;
    private static final int MSG_DELETE_FAILED = 7;
    private static final int MSG_LOAD_NOTNET = 8;

    private static final int SEND_SUCC = 10;
    private static final int SEND_FAIL = 11;
    private int pageNum;
    private int pageSize;
    private NetRequest netRequest;
    private Dialog alterDialog;
    AlertDialog.Builder builder;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {


                case MSG_LOAD_SUCCESS:
                    Log.v("zyl", "onLoadComplete");
                    lv.onLoadComplete();
                    if (msg.arg1 == pageNum) {
                        @SuppressWarnings("unchecked")
                        List<GuideShoppingAgreeBean> result = (List<GuideShoppingAgreeBean>) msg.obj;
                        lv.setResultSize(result.size());
                        list.addAll(result);
                        mAdapter.notifyDataSetChanged();
                        pageNum += 1;
                        if (list.size() == 0) {
//							lin_loadfail.setVisibility(View.VISIBLE);
//							img_fail_nonet.setVisibility(View.GONE);
//							img_fail_notext.setVisibility(View.VISIBLE);
//							tv_fail.setText("暂无内容");
                        }
                    }
                    break;
                case MSG_LOAD_FAILED:
                    lv.setResultSize(0);
                    lv.onLoadComplete();

                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_REFRESH_SUCCESS:
                    lv.onLoadComplete();
                    lv.onRefreshComplete();
                    @SuppressWarnings("unchecked")
                    List<GuideShoppingAgreeBean> result = (List<GuideShoppingAgreeBean>) msg.obj;
                    lv.setResultSize(result.size());
                    list.clear();
                    list.addAll(result);
                    mAdapter.notifyDataSetChanged();
                    pageNum += 1;
                    break;
                case MSG_REFRESH_FAILED:
                    lv.onRefreshComplete();
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_DELETE_SUCCESS:
                    lv.onRefresh();
                    break;
                case MSG_DELETE_FAILED:
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case SEND_FAIL:
                    Toast.makeText(getActivity(), "确认收货失败!", Toast.LENGTH_SHORT).show();
                    break;
                case SEND_SUCC:
//                    int position = (int) msg.obj;
//                    list.get(position).setStatus("received");
//                    mAdapter.notifyDataSetChanged();
//                    Toast.makeText(getActivity(), "确认收货成功!", Toast.LENGTH_SHORT).show();
                    break;
                //无网络
                case MSG_LOAD_NOTNET:
//					lin_loadfail.setVisibility(View.VISIBLE);
//					lin_loadfail.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//					lin_loadfail.setVisibility(View.GONE);
//						lv.onLoad();
//						}
//					});
                default:
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_guide_shopping, container, false);
        list = new ArrayList<>();
        pageNum = 1;
        pageSize = 15;
        findViews();
        setListeners();
        lv.onLoad();
        EventBus.getDefault().register(this);
        return v;
    }

    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(EventBusBean eventBusBean) {
        if(eventBusBean.type == 223){
            pageNum = 1;
            netRequest.requestSaleAssistantApprovedForStoresListPageFind(2, pageNum + "", pageSize + "");
        }
    }



    private void findViews() {
        netRequest = new NetRequest(this, getActivity());
        img_fail_nonet = (ImageView) v.findViewById(R.id.loadfail_nonet);
        img_fail_notext = (ImageView) v.findViewById(R.id.loadfail_notext);
        tv_fail = (TextView) v.findViewById(R.id.loadfail_tv);
        lv = (AutoListView) v.findViewById(R.id.lv_goods);
        lv.setDivider(null);


        mAdapter = new GuideShoppingAgreeAdapter(list, getActivity(), new GuideShoppingAgreeAdapter.OnClickOrder() {
            @Override
            public void deleteClick(final GuideShoppingAgreeBean bean) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("确定删除导购?")
                        .setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        netRequest.requestDeleteGuide(3,bean.getConsumer_id(),bean.getMobile(), MainActivity.member_id, Stores.stores_name);
                    }
                });
                builder.show();
            }
        });
        lv.setAdapter(mAdapter);
    }

    private void setListeners() {


        lv.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                pageNum = 1;
                netRequest.requestSaleAssistantApprovedForStoresListPageFind(2, pageNum + "", pageSize + "");
            }
        });

        lv.setOnLoadListener(new OnLoadListener() {

            @Override
            public void onLoad() {
                netRequest.requestSaleAssistantApprovedForStoresListPageFind(1, pageNum + "", pageSize + "");
            }
        });
    }

    @Override
    public void onAfinalFail() {

        if (getActivity() != null) {
            ToastUtils.showTextToast(getActivity(), "请检查本地网络");
        }
        if (lv != null) {
            lv.onRefreshComplete();
        }
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                Log.v("zyl", "data1:" + data.toString());
                Gson gson = new Gson();

                JSONArray listArr = data.getJSONArray("list");
                List<GuideShoppingAgreeBean> OrderBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    GuideShoppingAgreeBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(), GuideShoppingAgreeBean.class);
                    OrderBeanList.add(orderBean);
                }
                Message message = Message.obtain();
                message.what = MSG_LOAD_SUCCESS;
                message.arg1 = data.getJSONObject("page").getInt("page_no");
                message.obj = OrderBeanList;
                mHandler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 2) {
            try {
                JSONObject data = new JSONObject(result);
                Gson gson = new Gson();
                JSONArray listArr = data.getJSONArray("list");
                List<GuideShoppingAgreeBean> OrderBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    GuideShoppingAgreeBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(), GuideShoppingAgreeBean.class);
                    OrderBeanList.add(orderBean);
                }
                Message message = Message.obtain();
                message.what = MSG_REFRESH_SUCCESS;
                message.arg1 = data.getJSONObject("page").getInt("page_no");
                message.obj = OrderBeanList;
                mHandler.sendMessage(message);
            } catch (Exception e) {
            }
        } else if (requestId == 3) {
            //删除成功
            pageNum = 1;
            netRequest.requestSaleAssistantApprovedForStoresListPageFind(2, pageNum + "", pageSize + "");
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (msg.contains("重新登")) {

        } else {
            if (getActivity() != null) {
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }
        }
    }
}